﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;

namespace AgilePlannerDT.Utils
{
    class MicrosoftSurfaceVersionLocator
    {

        public MicrosoftSurfaceVersionLocator()
        {

        }

        public string findLatestVersion(string [] directoryNames)
        {
            return find(directoryNames);
        }

        public string findLatestVersion()
        {
            string version = null;
            RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("Software");

            if (softwareKey != null)
            {
                RegistryKey microsoftkey = softwareKey.OpenSubKey("Microsoft");

                if (microsoftkey != null)
                {
                    RegistryKey surfaceKey = microsoftkey.OpenSubKey("Surface");

                    if (surfaceKey != null)
                    {
                        string[] directoryNames = surfaceKey.GetSubKeyNames();
                        version = find(directoryNames);
                    }
                }
            }
            return version;
        }

        private string find(string[] directoryNames)
        {
            string version = null;
            var regExpression = new Regex(@"v\d\.\d");
            
            foreach (string directoryName in directoryNames)
            {
                if (regExpression.IsMatch(directoryName))
                {
                    version = directoryName;
                }
            }
            return version;
        }


    }
}
